<template>
  <div class="table-container">
    <el-table 
      :data="tableData" 
      :header-cell-style="headerStyle"
      :cell-style="cellStyle"
      stripe>
      <el-table-column 
        prop="title" 
        label="文章标题" 
        width="180"
        align="left"/>
      <el-table-column 
        prop="publish_time" 
        label="发布时间" 
        width="150"
        align="center">
        <template #default="scope">
          {{ formatDateTime(scope.row.publish_time) }}
        </template>
      </el-table-column>
      <el-table-column 
        prop="hits" 
        label="阅读量" 
        width="100"
        align="center"/>
      <el-table-column 
        prop="review_status" 
        label="审核状态" 
        width="120"
        align="center">
        <template #default="scope">
          <el-tag :type="getReviewStatusType(scope.row.review_status)">
            {{ getReviewStatusText(scope.row.review_status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column 
    label="详情" 
    width="100"
    align="center">
    <template #default="scope">
      <span class="button-text">
        <el-button 
          type="primary" 
          link 
          class="button-link"
          @click="handleView(scope.row)"
        >查看</el-button>
      </span>
    </template>
  </el-table-column>
  <el-table-column 
    label="操作" 
    width="100"
    align="center">
    <template #default="scope">
      <span class="button-text">
        <el-button 
          type="danger" 
          link 
          class="button-link"
          @click="handleDelete(scope.row)"
        >删除</el-button>
      </span>
    </template>
  </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="queryParams.Page"
        v-model:page-size="queryParams.Size"
        :total="total"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import ArticleApi from '@/api/article'
import { useUserInfoStore } from '@/stores/info'
import type { ArticleData, QueryParams } from '@/api/article/types'
import { useRouter } from 'vue-router'

const router = useRouter()
const userInfoStore = useUserInfoStore()
const tableData = ref<ArticleData[]>([])
const total = ref(0)

// 查询参数
const queryParams = reactive<QueryParams>({
  Page: 1,
  Size: 10,
  publisher_id: Number(userInfoStore.userInfo.user_id),
  is_delete: 0
})

// 时间格式化函数
const formatDateTime = (time: string | undefined) => {
  if (!time) return '--'
  const date = new Date(time)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

// 获取文章列表
const getArticleList = async () => {
    try {
    const res = await ArticleApi.getArticles(queryParams)
    if (Array.isArray(res.data)) {
        tableData.value = res.data
        total.value = res.data.total
      } else {
      ElMessage.error('获取文章列表失败')
    }
  } catch (error) {
    console.error('获取文章列表失败:', error)
    ElMessage.error('获取文章列表失败')
  }
}

// 获取审核状态样式
const getReviewStatusType = (status: number) => {
  switch (status) {
    case 0: return 'warning'    // 待审核
    case 1: return 'success' // 通过
    case 2: return 'danger'  // 拒绝
    default: return 'info'
  }
}

// 获取审核状态文本
const getReviewStatusText = (status: number) => {
  switch (status) {
    case 0: return '待审核'
    case 1: return '已通过'
    case 2: return '已拒绝'
    default: return '未知'
  }
}

// 分页处理
const handleSizeChange = (val: number) => {
  queryParams.Size = val
  queryParams.Page = 1
  getArticleList()
}

const handleCurrentChange = (val: number) => {
  queryParams.Page = val
  getArticleList()
}

// 查看详情
const handleView = (row: ArticleData) => {
  router.push({
    name: 'articleDetail',
    params: { id: row.article_id }
  })
}

// 删除文章
const handleDelete = async (row: ArticleData) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除文章 "${row.title}" 吗？`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const res = await ArticleApi.deleteArticle(row.article_id)
    if (res.data) {
      ElMessage.success('删除成功')
      getArticleList()
    } else {
      ElMessage.error(  '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除文章失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 表格样式
const headerStyle = {
  backgroundColor: '#f5f7fa',
  color: '#606266',
  fontWeight: '500'
}

const cellStyle = {
  padding: '12px 0'
}

onMounted(() => {
  getArticleList()
})
</script>

<style scoped>
.table-container {
  padding: 20px;
  background-color: #ffffff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  width: 750px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-table) {
  width: 100% !important;
  border: 1px solid #ebeef5;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: #fafafa;
}

:deep(.el-table__body tr:hover > td) {
  background-color: #f5f7fa !important;
}

:deep(.el-button--primary.is-link) {
  color: #409EFF;
}

:deep(.el-button--danger.is-link) {
  color: #F56C6C;
}

:deep(.button-link) {
  padding: 0;  /* 移除内边距 */
  margin: 0;   /* 移除外边距 */
}

:deep(.el-button--primary.is-link) {
  color: #409EFF;
}

:deep(.el-button--danger.is-link) {
  color: #F56C6C;
}

.button-text {
  display: inline-block;
  line-height: 1;
}

:deep(.button-link) {
  padding: 0;
  margin: 0;
  height: auto;
  line-height: 1;
}

:deep(.el-button--primary.is-link) {
  color: #409EFF;
}

:deep(.el-button--danger.is-link) {
  color: #F56C6C;
}
</style>